package com.zht.interceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.sql.Time;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.LocalTime;

@Component
@Slf4j
public class MyInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        log.info("requestURI:{}",requestURI);
        LocalDateTime beginTime = LocalDateTime.now();
        request.setAttribute("beginTime",beginTime);
        return true;

    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        String beginTime = request.getAttribute("beginTime").toString();
        log.info("beginTime:{}",beginTime);
        LocalDateTime endTime = LocalDateTime.now();
        String requestURI = request.getRequestURI();

        LocalDateTime begin = LocalDateTime.parse(beginTime);
        LocalDateTime end = LocalDateTime.parse(endTime.toString());
        Duration duration = Duration.between(begin,end);

        log.info("requestURI:{},endTime:{}",requestURI,endTime);
        log.info("时间差:{}",duration);



    }
}
